package panda.buffer;

import panda.file.Block;
import panda.file.Page;

public class Buffer {
	private Page page = new Page();

	private int pins = 0;

	private Block block = null;

	private int logSequenceNumber;

	private int modifiedBy = -1;

	public int getInt(int offset) {
		return page.getInt(offset);
	}

	public String getString(int offset) {
		return page.getString(offset);
	}
	
	public float getFloat(int offset){
		return page.getFloat(offset);
	}
	
	public long getLong(int offset){
		return page.getLong(offset);
	}
	
	public byte[] getArray(int offset){
		return page.getArray(offset);
	}
	
	public byte[] getArray(int offset, int length) {
		return page.getArray(offset,length);
	}
	
	public void memCpy(int fromPosition, int toPosition , int length , int transactionNumber, int lsn ){
		modifiedBy = transactionNumber;
		logSequenceNumber = lsn;
		page.memCpy(fromPosition,toPosition,length);
	}

	public void putInt(int offset, int value, int transactionNumber, int lsn) {
		modifiedBy = transactionNumber;
		logSequenceNumber = lsn;
//		System.out.println(block);
		page.putInt(offset, value);
//		System.out.println("===========");
	}

	public void putString(int offset, String value, int transactionNumber,
			int lsn) {
		modifiedBy = transactionNumber;
		logSequenceNumber = lsn;
//		System.out.println(block);
		page.putString(offset, value);
//		System.out.println("===========");
	}
	
	public void putFloat(int offset, float value,int transactionNumber,int lsn){
		modifiedBy = transactionNumber;
		logSequenceNumber = lsn;
		page.putFloat(offset, value);
	}
	
	public void putLong(int offset, long value, int transactionNumber, int lsn){
		modifiedBy = transactionNumber;
		logSequenceNumber = lsn;
		page.putLong(offset, value);
	}
	
	public void putArray(int offset, byte[] value, int transactionNumber, int lsn){
		modifiedBy = transactionNumber;
		logSequenceNumber =lsn;
		page.putArray(offset, value);
	}

	public String getFileName() {
		return block.getFileName();
	}

	public int getBlockNumber() {
		return block.getBlockNumber();
	}

	public Block getBlock() {
		return block;
	}

	public void pageOut() {
		panda.server.Panda.getLogManager().flush(logSequenceNumber);
		page.write(block);
		modifiedBy = -1;
	}

	boolean isModifiedBy(int transactionID) {
		return transactionID == modifiedBy;
	}

	void pageIn(Block b) {
		if (modifiedBy >= 0)
			pageOut();
		block = b;
		page.read(block);
		pins = 0;
	}

	void newPageIn(String fileName, PageFormatter formatter) {
		if (modifiedBy != -1)
			pageOut();
		formatter.format(page);
		block = page.append(fileName);
		pins = 0;
	}

	void pin() {
		pins++;
	}

	void unpin() {
		pins--;
	}

	boolean ispinned() {
		return pins > 0;
	}
}
